package com.zyy.rabbitmq.consumer;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.rabbitmq.client.Channel;
import com.zyy.rabbitmq.service.DispatcherService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Description: 类描述
 * @Author: zyy
 * @Date: 2023/06/12 21:45
 */
@Component
public class DeadOrderConsumer {

    @Autowired
    private DispatcherService dispatcherService;

    @RabbitListener(queues = "dead_order_dispatcher")
    public void messageReceive(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) {
        try {
            JSONObject messageJSON = JSON.parseObject(message);
            Integer orderId = messageJSON.getInteger("orderId");
            dispatcherService.createDispatcher(orderId);

            channel.basicAck(tag, false);
        } catch (Exception e) {
            /**
             * 死信队列还报错
             * 那么：
             * 人工干预
             * 预警
             * 同时把消息转移到别的存储db
             */
            try {
                channel.basicNack(tag, false, false);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

}
